package jwtx

import (
	"strings"

	"gitee.com/yanwc/gozero-utils/errx"
	jwt "github.com/golang-jwt/jwt/v5"
	"github.com/zeromicro/go-zero/core/jsonx"
)

type UserType string

const (
	Admin  = UserType("admin")
	Member = UserType("member")
)

type JwtTokenData struct {
	UserId      int64    `json:"userId"`
	AccessToken string   `json:"accessToken"`
	TenantId    int64    `json:"tenantId"`
	TenantCode  string   `json:"tenantCode"`
	UserType    UserType `json:"userType"`
}

type JwtTokenPayload struct {
	Aud  string       `json:"aud"`
	Exp  int64        `json:"exp"`
	Iss  string       `json:"iss"`
	Sub  string       `json:"sub"`
	Data JwtTokenData `json:"data"`
}

func NewJwtTokenData(token string) (*JwtTokenData, *errx.Error) {
	p := jwt.NewParser(jwt.WithStrictDecoding())
	segs := strings.Split(token, ".")
	dataSeg, err := p.DecodeSegment(segs[1])
	if err != nil {
		return nil, errx.NewWithError(errx.TOKEN_PARSER, err)
	}

	var payload JwtTokenPayload
	err = jsonx.Unmarshal(dataSeg, &payload)
	if err != nil {
		return nil, errx.NewWithError(errx.JSON_UNMARSHAL, err)
	}

	return &payload.Data, nil
}
